<?php

namespace app\admin\controller;

use app\admin\Validate\AdminUser;
use app\admin\Validate\ChangeAdmin;
use app\common\model\User;
use think\Controller;
use think\Db;
use think\facade\Validate;

class Login extends Controller
{
    public function login(){
        if(request()->isPost()){
            $user=input('param.');
            $checkData=(new AdminUser());
            if(!$checkData->check($user)){
                return $this->error($checkData->getError());
            }
            $admin=db('user')->where('user_name',$user['name'])->where('user_password',md5($user['password']))->where('user_type',1)->find();
            if(!$admin){
                return $this->error(" 用户名或密码错误");
            }else{
                session('name',$user['name']);
                (new User())->save(['lastlogin_time'=>time()],['user_id'=>$admin['user_id']]);
                $this->redirect('admin/index/index');

            }
        }
        return $this->fetch();
    }
    public function changepwd(){
        if(request()->isPost()){
            $admin=input('param.');
            $checkData=new ChangeAdmin();
            if(!$checkData->check($admin)){
                return $this->error($checkData->getError());
            }
            $user=Db::name('user')->find();
            if($user['user_password']==md5($admin['oldpwd'])){
                $newData=['user_password'=>md5($admin['newpwd'])];
                $change=Db::name('user')->where('user_id',$user['user_id'])->update($newData);
                if($change){
                    session(null);
                    return $this->success('修改成功','admin/login/login');
                }else{
                    return $this->error("修改失败");
                }
            }else{
                return $this->error("原密码错误");
            }

        }
        return $this->fetch();
    }
    public function layout(){
        session(null);
        $this->redirect('admin/login/login');
    }
}
